package com.yilin.xbr.common.converter;

import com.fasterxml.jackson.core.JsonGenerator;
import org.apache.log4j.Logger;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 数据返回JSON转化器-返回数据加密过程
 */
public class MyHttp2JsonConverter extends MappingJackson2HttpMessageConverter{
    Logger log = Logger.getLogger(MyHttp2JsonConverter.class);

    @Override
    protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
        super.writePrefix(generator,object);
    }

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        Map<String, Object> map = null;
        do {
            if (object != null) {
                map = (Map<String, Object>) object;
//                HttpServletRequest requset = AppUtil.getThreadLocalObjectForKey("REQUEST");
//                if (requset != null && map.containsKey("data")) {
//                    Account acc =  AppUtil.getThreadLocalObjectForKey("USER");
//                    String token = null;
//                    if (acc != null)  token = acc.getToken();
//                    Object data = map.get("data");
//                    if(map.containsKey("isEncrypt")) { //不加密
//                        Boolean isEncrypt =(Boolean) map.get("isEncrypt");
//                        if(!isEncrypt) {
//                            map.remove("isEncrypt");
//                            String json = JsonUtil.serializeToJson(data);
//                            map.put("data",json);
//                            break;
//                        }
//                    }
//                    if(data != null) {
//                        String json = JsonUtil.serializeToJson(data);
//                        if(StringUtil.isNotEmpty(json)) {
//                            try {
//                                map.put("data", EncryptUtils.encrypt(json,token));
//                            } catch (Exception e) {
//                                map.put("data", null);
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                }
            }
        } while (false);
        if(log.isInfoEnabled()){
            log.info(">>>>>>>>>>>> 返回信息："+ map.get("msg"));
            log.info(">>>>>>>>>>>> 是否成功："+ map.get("success"));
            log.info(">>>>>>>>>>>> 返回数据："+ map.get("data"));
        }
        super.writeInternal(map != null ? map : object, outputMessage);
    }
}

